package com.ellricky.newtv.utils

import android.app.Activity
import android.os.Handler
import com.andr.common.util.ToastUtil
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.newtv.NewTvApp
import com.zhy.http.okhttp.callback.StringCallback
import okhttp3.Call
import org.json.JSONObject

object CacheToken {

    fun verifyToken() {
        val tvUserInfo = LocalCacheUtil.readTvUserInfo()
        if (tvUserInfo != null) {
            val localToken = tvUserInfo.token
            val url = EAppUtil.getTvApiHost()
            val paramMap = mutableMapOf(
                "action" to "userKey",
                "token" to localToken,
                "eid" to tvUserInfo.eid
            )
            HttpUtils.getInstance()
                .postFrom(url, paramMap, object : StringCallback() {
                    override fun onError(call: Call?, e: Exception?, id: Int) {
                        e?.printStackTrace()
                    }

                    override fun onResponse(response: String?, id: Int) {
                        val isOk = response?.let {
                            val json = JSONObject(it)
                            val data = json.optString("isOk")
                            var result = ""
                            result = if (data.isEmpty()) {
                                "1"
                            } else {
                                data
                            }
                            result
                        }
                        if (isOk == "0") {
                            ToastUtil.show(NewTvApp.instance(), "登录已过期 10秒后即将关闭应用")
                            LocalCacheUtil.tvLogout()
                            Handler().postDelayed({
                                NewTvApp.instance().exit()
                            }, 10000)
                        }
                    }
                }, this)
        }
    }
}